package com.adminsystem.controller;

import cn.hutool.core.date.DateUtil;
import com.adminsystem.common.aop.AutoLog;
import com.adminsystem.common.utils.StringUtils;
import com.adminsystem.entity.*;
import com.adminsystem.entity.custom.PageBean;
import com.adminsystem.service.SysRoleService;
import com.adminsystem.service.SysUserRoleService;
import com.adminsystem.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.system.common.utils.CommonFileUtils;
import com.system.core.http.R;
import io.swagger.annotations.Api;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 *
 */
@RestController
@RequestMapping("/sys/user")
@Api(tags = "系统用户")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Value("${avatarImageFilePath}")
    private String avatarImageFilePath;

    @Value("${originPwd}")
    private String originPwd;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @PostMapping("/save")
    @PreAuthorize("hasAuthority('system:user:add')" + "||" + "hasAuthority('system:user:edit')" + "||" + "hasAuthority('system:user:updateBaseInfo')")
    @AutoLog("新增或编辑用户信息")
    public R saveUser(@RequestBody SysUser sysUser) {
        if (sysUser.getId() < 0) {
            Date d = new Date();
            sysUser.setCreateTime(d);
            sysUser.setUpdateTime(d);
            sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
            sysUserService.save(sysUser);
            //新创建的用户分配普通用户角色
            SysUserRole sysUserRole=new SysUserRole();
            sysUserRole.setUserId(sysUser.getId());
            sysUserRole.setRoleId(2L);
            sysUserRoleService.save(sysUserRole);
        } else {
            sysUser.setUpdateTime(new Date());
            sysUserService.updateById(sysUser);
        }
        return R.success(sysUser);
    }

    @PostMapping("/updateUserPwd")
    @PreAuthorize("hasAuthority('system:user:updateBaseInfo')")
    @AutoLog("修改用户密码")
    public R updateUserPwd(@RequestBody SysUser sysUser) {
        SysUser currentUser = sysUserService.getById(sysUser.getId());
        if (bCryptPasswordEncoder.matches(sysUser.getOldPassword(), currentUser.getPassword())) {
            var newPassWord = bCryptPasswordEncoder.encode(sysUser.getNewPassword());
            currentUser.setPassword(newPassWord);
            currentUser.setUpdateTime(new Date());
            if (sysUserService.updateById(currentUser)) {
                return R.success("密码修改成功,下次登录生效", currentUser);
            } else {
                return R.error(500, "密码修改失败");
            }
        } else {
            return R.error(500, "原密码错误");
        }
    }

    @PostMapping("/uploadImage")
    @PreAuthorize("hasAuthority('system:user:uploadUserAvatar')")
    @AutoLog("上传用户头像")
    public R uploadImage(MultipartFile file) throws Exception {
        Map<String, Object> dataMap = new HashMap<>();
        if (!file.isEmpty()) {
            String originalFileName = file.getOriginalFilename();
            String suffixName = originalFileName.substring(originalFileName.lastIndexOf("."));
            String newFileName = DateUtil.format(new Date(), "yyyyMMddHHmmss") + "_" + UUID.randomUUID().toString() + suffixName;
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(avatarImageFilePath + newFileName));
            dataMap.put("fileName", newFileName);
            dataMap.put("src", "image/userAvatar/" + newFileName);
        }
        return R.success("上传成功", dataMap);
    }

    @PostMapping("/updateAvatar")
    @PreAuthorize("hasAuthority('system:user:updateBaseInfo')")
    @AutoLog("更新用户头像")
    public R updateAvatar(@RequestBody SysUser sysUser) {
        SysUser currentUser = sysUserService.getById(sysUser.getId());
        currentUser.setUpdateTime(new Date());
        currentUser.setAvatar(sysUser.getAvatar());
        sysUserService.updateById(sysUser);
        return R.success("更新头像成功", sysUser);
    }

    @PostMapping("/list")
    @PreAuthorize("hasAuthority('system:user:list')")
    public R list(@RequestBody PageBean pageBean) {
        String query = pageBean.getQuery().trim();
        Page<SysUser> pageResult = sysUserService.page(
                new Page<>(pageBean.getPageNum(),
                        pageBean.getPageSize()),
                new QueryWrapper<SysUser>()
                        .select("id", "avatar", "username", "email", "phonenumber", "status", "update_time,create_time")
                        .like(StringUtils.isNotEmpty(query), "username", query)
                        .ne("is_delete", "1")
                        .orderByDesc("update_time"));
        List<SysUser> userList = pageResult.getRecords();
        for (SysUser user : userList) {
            List<SysRole> roleList = sysRoleService.list(new QueryWrapper<SysRole>().inSql("id", "select role_id from sys_user_role where user_id= " + user.getId()));
            user.setSysRoleList(roleList);
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("userList", userList);
        resultMap.put("total", pageResult.getTotal());

        return R.success(resultMap);
    }

    @PostMapping("/export")
//    @PreAuthorize("hasAuthority('system:user:downfile')")
    public void downFile(@RequestBody PageBean pageBean, HttpServletResponse res) {
        File file = sysUserService.createUserExcelFile(pageBean);
        CommonFileUtils.downloadFile(res, file, file.getName());
    }

    @GetMapping("/{id}")
    @PreAuthorize("hasAuthority('system:user:query')")
    @AutoLog("查询用户信息")
    public R findById(@PathVariable(value = "id") Integer id) {
        SysUser sysUser = sysUserService.getById(id);
        Map<String, Object> map = new HashMap<>();
        map.put("sysUser", sysUser);
        return R.success(map);
    }

    @PostMapping("/checkUserName")
    @PreAuthorize("hasAuthority('system:user:query')")
    public R checkUserName(@RequestBody SysUser sysUser) {
        if (sysUserService.getByUserName(sysUser.getUsername()) == null) {
            return R.success();
        } else {
            return R.error();
        }
    }
    @PostMapping("/checkPhone")
    @PreAuthorize("hasAuthority('system:user:query')")
    public R checkPhone(@RequestBody SysUser sysUser) {
        if (sysUserService.getByPhone(sysUser.getPhonenumber()) == null) {
            return R.success();
        } else {
            return R.error();
        }
    }
    @PostMapping("/checkEmail")
    @PreAuthorize("hasAuthority('system:user:query')")
    public R checkEmail(@RequestBody SysUser sysUser) {
        if (sysUserService.getByEmail(sysUser.getEmail()) == null) {
            return R.success();
        } else {
            return R.error();
        }
    }
    /**
     * @param ids
     * @return
     */
    @Transactional
    @PostMapping("/delete")
    @PreAuthorize("hasAuthority('system:user:delete')")
    @AutoLog("删除用户信息")
    public R delete(@RequestBody List<SysUser> sysUserList) {
//        List<Long> idList = Arrays.stream(ids).boxed().collect(Collectors.toList());
        //超级管理员不能删除
        sysUserList.removeIf(n -> n.getId() == 1);
        sysUserList.forEach(t -> {
            t.setIsDelete("1");
        });
        System.out.println("sysUserList:" + sysUserList);
        sysUserService.saveOrUpdateBatch(sysUserList);
        System.out.println("sysUserList:" + sysUserList);

        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().in("user_id",
                sysUserList.stream().map(SysUser::getId)
                        .collect(Collectors.toList())));
        return R.success();
    }

    @GetMapping("/resetPwd/{id}")
    @PreAuthorize("hasAuthority('system:user:edit')")
    @AutoLog("初始化用户名密码")
    public R resetPwd(@PathVariable Long id) {
        SysUser currentUser = sysUserService.getById(id);
        currentUser.setUpdateTime(new Date());
        currentUser.setPassword(bCryptPasswordEncoder.encode(originPwd));
        sysUserService.updateById(currentUser);
        return R.success("重置密码成功");
    }

    @PostMapping("/updateUserStatus")
    @PreAuthorize("hasAuthority('system:user:edit')")
    @AutoLog("更新用户状态")
    public R updateUserStatus(@RequestBody SysUser sysUser) {
        SysUser currentUser = sysUserService.getById(sysUser.getId());
        currentUser.setUpdateTime(new Date());
        currentUser.setStatus(sysUser.getStatus());
        sysUserService.updateById(currentUser);
        return R.success("更新用户状态成功");
    }
}
